<?php

namespace app\index\controller;

use app\admin\model\Pmsorderinfo;
use app\common\controller\Frontend;
use services\QCloudSmsService;
use think\Config;
use think\Cookie;
use think\Db;
use think\Hook;
use think\Model;
use think\Validate;

class Index extends Frontend
{
    protected $noNeedLogin = ['index', 'login'];
    protected $noNeedRight = '*';
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        Hook::add('user_login_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id, 86400);
            Cookie::set('token', $auth->getToken(), 86400);
        });

        //监听注册登录退出的事件
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });

        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
    }

    public function index()
    {
        return $this->fetch('');
    }

    public function login()
    {
        if ($this->auth->id) {
            $this->redirect('checkIn');
        }
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $captcha = $this->request->post('captcha');
            $rule    = [
                'account' => 'require|length:3,50',
            ];

            $msg = [
                'account.require' => 'Account can not be empty',
                'account.length'  => 'Account must be 3 to 50 characters',
            ];

            $validate = new Validate($rule, $msg);
            $result   = $validate->check(compact('account'));
            if (!$result) {
                $this->error(__((string)$validate->getError()));
            }
            if ($captcha != session('captcha')) {
                $this->error(__('验证码错误!'));
            }
            $res = $this->auth->login($account);
            if ($res === 10001) {
                if ($this->auth->register($account, '', '', $account)) {
                    $this->success(__('Logged in successful'));
                } else {
                    $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                }
            } elseif ($res === true) {
                $this->success(__('Logged in successful'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Login'));
        return $this->fetch();
    }

    public function checkIn()
    {
        $this->assign('date', date('Y-m-d'));
        $this->assign('endDate', date('Y-m-d', strtotime('+2 month +2day')));
        return $this->fetch();
    }

    public function order()
    {
        $date = $this->request->get('date', '');
        if (!$date) {
            $this->error(__('无效日期！'));
        }
        $this->assign('mobile', $this->auth->mobile);
        $this->assign(compact('date'));
        return $this->fetch();
    }

    public function orderSuc()
    {
        return $this->fetch();
    }

    public function user()
    {
        $m           = new Pmsorderinfo();
        $reservation = Db::name('reservation')->where('uid', $this->auth->id)
            ->order('id desc')->select()->toArray();
        foreach ($reservation as &$item) {
            $item['order'] = [];
            if ($item['status'] == 1) {
                $item['order'] = $m->where('reserve_id', $item['id'])->field('id,order_status')->find()->toArray();
            }
        }

        $this->assign('list', $reservation);
        return $this->fetch();
    }

    public function create()
    {
        $arg = $this->request->post();
        if (empty($arg)) {
            $this->error('服务器错误');
        }

        $arg['uid']       = $this->auth->id;
        $arg['over_date'] = date('Y-m-d', strtotime($arg['stay_date']) + ($arg['stay_days'] * 86400));
        $arg['is_allow_change_date'] = $arg['is_allow_change_date'] ?? 0;
        $res              = Db::name('reservation')->insert($arg);
        if ($res) {
            $this->success('成功');
        }
        $this->error(__('失败'));
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        if ($this->request->isPost()) {
            // $this->token();
            //退出本站
            $this->auth->logout();
            $this->success(__('Logout successful'));
        }
    }

    public function revoke()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error(__('系统错误'));
        }
        if (!Db::name('reservation')->where('id', $id)->update(['status' => 3])) {
            $this->error(__('撤销失败'));
        }
        $this->success('撤销成功');
    }

    public function cancelOrder(int $oid, int $id, string $date)
    {
        Db::name('reservation')->where('id', $id)->update(['status' => 4]);
        (new Pmsorderinfo())->where(['id' => $oid])->update(['order_status' => 2]);
        QCloudSmsService::create($this->auth->mobile)->sendUserCancelSms($date);
        $this->success('取消预约成功');
    }
}
